package cn.bytecollege.admin.controller;

import cn.bytecollege.admin.service.CategoryService;
import cn.bytecollege.common.constant.Resource;
import cn.bytecollege.common.entity.Category;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "CategoryUpdateController", value = "/admin/categoryUpdate")
public class CategoryUpdateController extends HttpServlet {
    private CategoryService categoryService=null;
    public CategoryUpdateController(){
        categoryService=new CategoryService();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg=null;
        //1.获取请求参数
        String id=request.getParameter("id");
        String name=request.getParameter("categoryName");

        Category category=categoryService.findByCategoryName(name);
        Category tempCategory=new Category();

        tempCategory.setCategoryId(Integer.valueOf(id));
        tempCategory.setCategoryName(name);
        if(category!=null){
            msg="分类已经存在，请更换其他名称！";
            request.setAttribute("msg",msg);
            //显示重复名称
            request.setAttribute("category",tempCategory);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/categoryUpdate.jsp").forward(request,response);
            return;
        }
        categoryService.update(tempCategory);
        response.sendRedirect(request.getContextPath()+"/admin/categoryList");

    }
}
